<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>员工工时</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <div class="hourTabs-header">
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          项目名称
          <el-select
            v-model="formInline.proId"
            @change="getCycle"
            filterable
            auto-complete="off"
            placeholder="请选择"
          >
            <el-option label="无" value></el-option>
            <!-- 循环所有项目 项目名称 项目ID -->
            <el-option
              v-for="(item,index) in proList"
              :key="index"
              :label="item.proName"
              :value="item.id"
            ></el-option>
          </el-select>
          <el-button
            style="float:right;font-weight: 400;"
            v-if="btnAdd"
            icon="el-icon-document-add"
            type="success"
            @click="addHandle"
          >添加</el-button>

          <!-- 个人工时列表暂无上传下载操作
          <el-button type="primary" size="medium" style="float:right;" v-if="btnUpload">
            <i class="fa fa-cloud-upload" aria-hidden="true"></i> 上传
          </el-button>
          <el-button type="success" size="medium" style="float:right;" v-if="btnDown">
            <i class="fa fa-cloud-download" aria-hidden="true"></i> 下载
          </el-button>
          -->
        </el-row>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick" class="hourTabs">
        <el-tab-pane label="年度工时" name="first">
          <div class="year-hours-middle">
            <!-- 查询条件 -->
            <el-row class="table-selbox" v-if="btnSel">
              <!-- 查询条件表单 -->
              <el-form :inline="true" :model="formInline" >
                <el-form-item label="年份" prop="year">
                  <el-date-picker v-model="formInline.year" type="year" placeholder="选择年"></el-date-picker>
                </el-form-item>
                <!-- 搜索 -->
                <el-form-item>
                  <el-button icon="el-icon-search" @click="selYearHandle">搜索</el-button>
                </el-form-item>
                <el-form-item style="float:right;" label="项目周期">
                  <el-date-picker
                    v-model="formInline.cycle"
                    disabled
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-form>
            </el-row>
            <!-- 数据列表 -->
            <el-table
              :data="yearData"
              show-summary
              :summary-method="getYearSummaries"
              border
              style="width: 100%"
              height="395"
              ref="yearData"
            >
              <!-- 项目名称 -->
              <el-table-column
                :show-overflow-tooltip="true"
                prop="proName"
                label="项目名称"
                width="200"
                fixed
              ></el-table-column>
              <!-- 1月 -->
              <el-table-column sortable prop="month1" label="1月" width="100"></el-table-column>
              <!-- 2月 -->
              <el-table-column sortable prop="month2" label="2月" width="100"></el-table-column>
              <!-- 3月 -->
              <el-table-column sortable prop="month3" label="3月" width="100"></el-table-column>
              <!-- 4月 -->
              <el-table-column sortable prop="month4" label="4月" width="100"></el-table-column>
              <!-- 5月 -->
              <el-table-column sortable prop="month5" label="5月" width="100"></el-table-column>
              <!-- 6月 -->
              <el-table-column sortable prop="month6" label="6月" width="100"></el-table-column>
              <!-- 7月 -->
              <el-table-column sortable prop="month7" label="7月" width="100"></el-table-column>
              <!-- 8月 -->
              <el-table-column sortable prop="month8" label="8月" width="100"></el-table-column>
              <!-- 9月 -->
              <el-table-column sortable prop="month9" label="9月" width="100"></el-table-column>
              <!-- 10月 -->
              <el-table-column sortable prop="month10" label="10月" width="100"></el-table-column>
              <!-- 11月 -->
              <el-table-column sortable prop="month11" label="11月" width="100"></el-table-column>
              <!-- 12月 -->
              <el-table-column sortable prop="month12" label="12月" width="100"></el-table-column>
              <!-- 合计 -->
              <el-table-column sortable label="合计" fixed="right" align="center" width="160">
                <template slot-scope="scope">
                  {{
                  scope.row.month1 + scope.row.month2 + scope.row.month3 + scope.row.month4
                  + scope.row.month5 + scope.row.month6 + scope.row.month7 + scope.row.month8
                  + scope.row.month9 + scope.row.month10 + scope.row.month11 + scope.row.month12
                  }}
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="table-pageblock">
              <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
              <el-pagination
                @size-change="yearHandleSizeChange"
                @current-change="yearHandleCurrentChange"
                :current-page="yearCurrentPage"
                :page-sizes="[20,50,80,100]"
                :page-size="yearPageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="yearTotal"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="月度工时" name="second">
          <div class="month-hours-middle">
            <!-- 查询条件 -->
            <el-row class="table-selbox">
              <!-- 查询条件表单 -->
              <el-form :inline="true" :model="formInline" >
                <el-form-item label="月份" prop="month">
                  <el-date-picker type="month" placeholder="选择月" v-model="formInline.month"></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" @click="selMonthHandle">搜索</el-button>
                </el-form-item>
                <el-form-item style="float:right;" label="项目周期">
                  <el-date-picker
                    v-model="formInline.cycle"
                    disabled
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-form>
            </el-row>
            <!-- 数据列表 -->
            <el-table
              :data="monthData"
              show-summary
              :summary-method="getMonthSummaries"
              border
              style="width: 100%"
              height="395"
              ref="monthData"
            >
              <!-- 项目名称 -->
              <el-table-column
                :show-overflow-tooltip="true"
                prop="proName"
                label="项目名称"
                width="200"
                fixed
              ></el-table-column>
              <!-- 1日 -->
              <el-table-column sortable prop="day1" label="1日" width="100"></el-table-column>
              <!-- 2日 -->
              <el-table-column sortable prop="day2" label="2日" width="100"></el-table-column>
              <!-- 3日 -->
              <el-table-column sortable prop="day3" label="3日" width="100"></el-table-column>
              <!-- 4日 -->
              <el-table-column sortable prop="day4" label="4日" width="100"></el-table-column>
              <!-- 5日 -->
              <el-table-column sortable prop="day5" label="5日" width="100"></el-table-column>
              <!-- 6日 -->
              <el-table-column sortable prop="day6" label="6日" width="100"></el-table-column>
              <!-- 7日 -->
              <el-table-column sortable prop="day7" label="7日" width="100"></el-table-column>
              <!-- 8日 -->
              <el-table-column sortable prop="day8" label="8日" width="100"></el-table-column>
              <!-- 9日 -->
              <el-table-column sortable prop="day9" label="9日" width="100"></el-table-column>
              <!-- 10日 -->
              <el-table-column sortable prop="day10" label="10日" width="100"></el-table-column>

              <!-- 11日 -->
              <el-table-column sortable prop="day11" label="11日" width="100"></el-table-column>
              <!-- 12日 -->
              <el-table-column sortable prop="day12" label="12日" width="100"></el-table-column>
              <!-- 13日 -->
              <el-table-column sortable prop="day13" label="13日" width="100"></el-table-column>
              <!-- 14日 -->
              <el-table-column sortable prop="day14" label="14日" width="100"></el-table-column>
              <!-- 15日 -->
              <el-table-column sortable prop="day15" label="15日" width="100"></el-table-column>
              <!-- 16日 -->
              <el-table-column sortable prop="day16" label="16日" width="100"></el-table-column>
              <!-- 17日 -->
              <el-table-column sortable prop="day17" label="17日" width="100"></el-table-column>
              <!-- 18日 -->
              <el-table-column sortable prop="day18" label="18日" width="100"></el-table-column>
              <!-- 19日 -->
              <el-table-column sortable prop="day19" label="19日" width="100"></el-table-column>
              <!-- 20日 -->
              <el-table-column sortable prop="day20" label="20日" width="100"></el-table-column>

              <!-- 21日 -->
              <el-table-column sortable prop="day21" label="21日" width="100"></el-table-column>
              <!-- 22日 -->
              <el-table-column sortable prop="day22" label="22日" width="100"></el-table-column>
              <!-- 23日 -->
              <el-table-column sortable prop="day23" label="23日" width="100"></el-table-column>
              <!-- 24日 -->
              <el-table-column sortable prop="day24" label="24日" width="100"></el-table-column>
              <!-- 25日 -->
              <el-table-column sortable prop="day25" label="25日" width="100"></el-table-column>
              <!-- 26日 -->
              <el-table-column sortable prop="day26" label="26日" width="100"></el-table-column>
              <!-- 27日 -->
              <el-table-column sortable prop="day27" label="27日" width="100"></el-table-column>
              <!-- 28日 -->
              <el-table-column sortable prop="day28" label="28日" width="100"></el-table-column>
              <!-- 29日 -->
              <el-table-column sortable prop="day29" label="29日" width="100"></el-table-column>
              <!-- 30日 -->
              <el-table-column sortable prop="day30" label="30日" width="100"></el-table-column>
              <!-- 31日 -->
              <el-table-column sortable prop="day31" label="31日" width="100"></el-table-column>

              <!-- 合计 -->
              <el-table-column sortable label="合计" fixed="right" align="center" width="160">
                <template slot-scope="scope">
                  {{
                  scope.row.day1 + scope.row.day2 + scope.row.day3 + scope.row.day4 + scope.row.day5 + scope.row.day6 + scope.row.day7 + scope.row.day8 + scope.row.day9 + scope.row.day10
                  + scope.row.day11 + scope.row.day12 + scope.row.day13 + scope.row.day14 + scope.row.day15 + scope.row.day16 + scope.row.day17 + scope.row.day18 + scope.row.day19 + scope.row.day20
                  + scope.row.day21 + scope.row.day22 + scope.row.day23 + scope.row.day24 + scope.row.day25 + scope.row.day26 + scope.row.day27 + scope.row.day28 + scope.row.day29 + scope.row.day30
                  + scope.row.day31
                  }}
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="table-pageblock">
              <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
              <el-pagination
                @size-change="monthHandleSizeChange"
                @current-change="monthHandleCurrentChange"
                :current-page="monthCurrentPage"
                :page-sizes="[20,50,80,100]"
                :page-size="monthPageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="monthTotal"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="工时记录" name="third">
          <div class="log-hours-middle">
            <!-- 查询条件 -->
            <el-row class="table-selbox" v-if="btnSel">
              <!-- 查询条件表单 -->
              <el-form :inline="true" :model="formInline" >
                <el-form-item label="日期">
                  <el-date-picker v-model="formInline.logTime" type="date" placeholder="选择日期"></el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
                </el-form-item>
                <el-form-item style="float:right;" label="项目周期">
                  <el-date-picker
                    v-model="formInline.cycle"
                    disabled
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                  ></el-date-picker>
                </el-form-item>
              </el-form>
            </el-row>
            <!-- 数据列表 -->
            <el-table :data="menusData" border style="width: 100%" ref="menusData">
              <!-- 项目名称 -->
              <el-table-column :show-overflow-tooltip="true" prop="proName" label="项目名称"></el-table-column>
              <!-- 日期 -->
              <el-table-column align="center" sortable label="日期" width="150" prop="logTime"></el-table-column>
              <!-- 工时数 -->
              <el-table-column align="center" sortable label="工时数" width="100" prop="hourNum"></el-table-column>
              <!-- 填写人 -->
              <el-table-column align="center" label="员工" width="150">
                <template slot-scope="scope">
                  {{scope.row.userName}} [{{scope.row.userId}}]
                </template>
              </el-table-column>
              <!-- 操作列 -->
              <el-table-column
                label="管理"
                fixed="right"
                align="center"
                width="100"
                v-if="[btnDel,btnEdit].indexOf(true) > -1"
              >
                <template slot-scope="scope">
                  <!-- 删除 -->
                  <el-button
                    size="mini"
                    @click="handleDelete(scope.row)"
                    type="danger"
                    v-if="btnDel"
                    :disabled="isDis(scope.row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="table-pageblock">
              <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[20,50,80,100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 弹窗 新增 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <!-- 添加 修改弹窗表单 -->
      <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
        <!-- 项目名称 -->
        <el-form-item label="项目名称" prop="proId">
          <el-select
            v-model="editForm.proId"
            filterable
            auto-complete="off"
            placeholder="请选择"
            style="width:100%;"
          >
            <!-- 循环所有项目 项目名称 项目ID -->
            <el-option
              v-for="(item,index) in proList"
              :key="index"
              :label="item.proName"
              :value="[item.id,item.proName]"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 日期 -->
        <el-form-item label="选择日期">
          <el-date-picker
            type="date"
            v-model="editForm.day"
            placeholder="选择日期"
            @change="getHours(editForm.day)"
            :picker-options="pickerOptions"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
        <div class="dcal-hours">
          <ul v-if="hours.length === 7">
            <li>
              <label>星期一</label>
              <span>{{hours[0].day}}</span>
              <span v-if="hours[0].placeholder > 12">剩余{{hours[0].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[0].placeholder}}</span>
              <el-input-number
                v-model="editForm.day1"
                :min="0"
                :max="hours[0].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[0].placeholder"
                size="small"
              ></el-input-number>
            </li>
            <li>
              <label>星期二</label>
              <span>{{hours[1].day}}</span>
              <span v-if="hours[1].placeholder > 12">剩余{{hours[1].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[1].placeholder}}</span>
              <el-input-number
                v-model="editForm.day2"
                :min="0"
                :max="hours[1].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[1].placeholder"
                size="small"
              ></el-input-number>
            </li>
            <li>
              <label>星期三</label>
              <span>{{hours[2].day}}</span>
              <span v-if="hours[2].placeholder > 12">剩余{{hours[2].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[2].placeholder}}</span>
              <el-input-number
                v-model="editForm.day3"
                :min="0"
                :max="hours[2].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[2].placeholder"
                size="small"
              ></el-input-number>
            </li>
            <li>
              <label>星期四</label>
              <span>{{hours[3].day}}</span>
              <span v-if="hours[3].placeholder > 12">剩余{{hours[3].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[3].placeholder}}</span>
              <el-input-number
                v-model="editForm.day4"
                :min="0"
                :max="hours[3].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[3].placeholder"
                size="small"
              ></el-input-number>
            </li>
            <li>
              <label>星期五</label>
              <span>{{hours[4].day}}</span>
              <span v-if="hours[4].placeholder > 12">剩余{{hours[4].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[4].placeholder}}</span>
             <el-input-number
                v-model="editForm.day5"
                :min="0"
                :max="hours[4].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[4].placeholder"
                size="small"
              ></el-input-number>
            </li>
            <li>
              <label>星期六</label>
              <span>{{hours[5].day}}</span>
              <span v-if="hours[5].placeholder > 12">剩余{{hours[5].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[5].placeholder}}</span>
              <el-input-number
                v-model="editForm.day6"
                :min="0"
                :max="hours[5].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[5].placeholder"
                size="small"
              ></el-input-number>
            </li>
            <li>
              <label>星期天</label>
              <span>{{hours[6].day}}</span>
             <span v-if="hours[6].placeholder > 12">剩余{{hours[6].placeholder}}</span>
              <span v-else class="hourAlert">剩余{{hours[6].placeholder}}</span>
              <el-input-number
                v-model="editForm.day7"
                :min="0"
                :max="hours[6].total"
                :controls="false"
                :step="4"
                step-strictly
                :placeholder="'最大值' + hours[6].placeholder"
                size="small"
              ></el-input-number>
            </li>
          </ul>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 取消 关闭弹窗 -->
        <el-button @click.native="dialogFormVisible=false">取消</el-button>
        <!-- 添加 初始化弹窗表单数据 -->
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="createData"
          :disabled="isSubmit"
        >添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入时间格式化插件
import moment from 'moment';
// 引入接口请求
// import axios from 'axios';

export default {
  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 当前页面数据
  data () {
    return {
      activeName: 'first',

      // 防止重复提交
      isSubmit: false,

      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 搜索条件
      formInline: {
        proId: '',
        cycle: [],
        logTime: '',
        year: '',
        month: ''
      },

      proList: [],

      // 列表数据
      monthData: [{}],
      // 当前页
      monthCurrentPage: 1,
      // 当前数
      monthPageSize: 20,
      // 总条目数
      monthTotal: 20,

      // 列表数据
      yearData: [{}],
      // 当前页
      yearCurrentPage: 1,
      // 当前数
      yearPageSize: 20,
      // 总条目数
      yearTotal: 20,

      // 列表数据
      menusData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',
      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '添加信息'
      },

      // 弹窗是否显示
      dialogFormVisible: false,

      // 编辑界面输入框校验规则
      editFormRules: {
        proId: [{ required: true, message: '请选择项目', trigger: 'change' }]
      },

      // 界面默认数据
      editForm: {
        proId: [],
        day: '',
        day1: 0,
        day2: 0,
        day3: 0,
        day4: 0,
        day5: 0,
        day6: 0,
        day7: 0
      },

      weekday: [],
      hours: [],

      endDay: '',

      // 日期控件可选范围
      pickerOptions: {
        disabledDate: time => {
          let date = new Date();
          let year = date.getFullYear();
          let month = date.getMonth() + 1;
          if (month >= 1 && month <= 9) {
            month = '0' + month;
          }
          let currentdate = year.toString() + month.toString();

          let timeyear = time.getFullYear();
          let timemonth = time.getMonth() + 1;

          if (timemonth >= 1 && timemonth <= 9) {
            timemonth = '0' + timemonth;
          }
          let timedate = timeyear.toString() + timemonth.toString();
          return currentdate > timedate;
        }
      }
    };
  },

  // 实例创建后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有项目
    this.getProlist();

    // 获取下个月的第一周的结束日期
    this.nextWeek();

    // 加载分页数据
    this.getYearDataByPage();
  },

  methods: {
    handleClick (tab, event) {
      this.activeName = tab.name;
      if (this.activeName === 'first') {
        this.getYearDataByPage();
      }
      if (this.activeName === 'second') {
        this.getMonthDataByPage();
      }
      if (this.activeName === 'third') {
        this.getmenusDataByPage();
      }
    },

    // 屏蔽删除按钮
    isDis (day) {
      let date = new Date();
      let enddate = moment(
        new Date(
          new Date().getFullYear(),
          new Date().getMonth() - 1,
          new Date(date.getFullYear(), date.getMonth(), 0).getDate()
        )
      ).format('YYYY-MM-DD');
      if (day.logTime > this.endDay) {
        return true;
      }
      if (day.logTime <= enddate) {
        return true;
      }
    },

    // 根据项目ID获取对应项目周期
    getCycle () {
      let params = {
        proId: this.formInline.proId ? this.formInline.proId : ''
      };
      if (params.proId !== '') {
        this.$http
          .post('/api/findProById', params)
          .then(res => {
            let { code, datas } = res;
            if (code === 0) {
              this.formInline.cycle = [datas.cycleStart, datas.cycleEnd];
              this.editForm.proId = datas.id;
            }
          })
          .catch(err => {
            if (err === undefined) {
              this.$message({
                message: '服务器响应异常！',
                type: 'error'
              });
              return false;
            }
          });
      } else {
        this.formInline.cycle = [];
      }
    },

    // 删除
    handleDelete (data) {
      // 删除二次确认弹窗
      this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 修改状态，逻辑删除
        let params = [data.id];

        // 根据所选列的ID删除对应数据
        this.$http.raw('api/batchDelWorks', params).then(res => {
          let { code } = res;
          if (code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功！'
            });
            // 刷新列表
            this.getmenusDataByPage();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 显示新增界面
    addHandle: function () {
      // 弹窗类型
      this.dialogStatus = 'create';
      // 弹窗显示状态
      this.dialogFormVisible = true;
      // 重置新增界面默认数据
      this.editForm = {
        proId: '',
        day: ''
      };
      this.hours = [];
    },

    // 选择项目 选择日期 获取对应工时
    getHours (date) {
      // 每次选择日期重置
      this.hours = [];
      this.editForm.day1 = 0;
      this.editForm.day2 = 0;
      this.editForm.day3 = 0;
      this.editForm.day4 = 0;
      this.editForm.day5 = 0;
      this.editForm.day6 = 0;
      this.editForm.day7 = 0;

      // 根据所选日期判断是否符合可选范围
      let day = moment(new Date(date).getTime()).format('YYYY-MM-DD');
      // 判断是否符合  不符合重置所选内容
      if (moment(day) > moment(this.endDay)) {
        this.$message({
          message: '当前日期不可选！',
          type: 'error'
        });
        this.editForm.day = '';
        this.hours = [];
      } else {
        // 符合获取对应周日期
        let monday = moment(day)
          .weekday(1)
          .format('YYYY-MM-DD');
        let tuesday = moment(day)
          .weekday(2)
          .format('YYYY-MM-DD');
        let wednesday = moment(day)
          .weekday(3)
          .format('YYYY-MM-DD');
        let thursday = moment(day)
          .weekday(4)
          .format('YYYY-MM-DD');
        let friday = moment(day)
          .weekday(5)
          .format('YYYY-MM-DD');
        let saturday = moment(day)
          .weekday(6)
          .format('YYYY-MM-DD');
        let sunday = moment(day)
          .weekday(7)
          .format('YYYY-MM-DD');

        // 根据周日期获取对应剩余工时
        let weeks = [
          monday,
          tuesday,
          wednesday,
          thursday,
          friday,
          saturday,
          sunday
        ];

        this.weekday = weeks;

        let params = {
          logTimes: weeks
        };

        this.$http.raw('/api/findAllWorksByTimeAndProId', params).then(res => {
          let { code, datas } = res;
          if (code === 0) {
            let wdhours = [];
            datas.map(item => {
              wdhours.push({
                day: item.logTime,
                total: item.syWorks,
                placeholder: item.syWorks
              });
            });
            this.hours = wdhours;
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }

      // 传递参数请求  同步异步请求
      // this.wdHour(weeks);
      // this.hours = JSON.parse(sessionStorage.getItem('wdhours'));
    },

    // 同步异步请求
    // async wdHour (weeks) {
    //   let arr = weeks;
    //   let res = '';
    //   for (const item of arr) {
    //     let params = {
    //       logTimes: item
    //     };
    //     res = await this.$http.raw('/api/findAllWorksByTimeAndProId', params).then(res => {
    //       let {code, datas} = res;
    //       if (code === 0) {
    //         return datas;
    //       }
    //     }).catch(err => {
    //       if (err === undefined) {
    //         this.$message({
    //           message: '服务器响应异常！',
    //           type: 'error'
    //         });
    //         return false;
    //       }
    //     });
    //   }

    //   // 日期排序
    //   arr.map((item, index) => {
    //     res.map((key) => {
    //       if (item === key.logTime) {
    //         arr.splice(index, 0);
    //         arr[index] = key;
    //       }
    //     });
    //   });

    //   // 循环排序赋值
    //   let wdhours = [];
    //   arr.map(ind => {
    //     if (typeof ind === 'string') {
    //       wdhours.push({
    //         day: ind,
    //         hour: 0,
    //         total: 24,
    //         placeholder: '剩余24'
    //       });
    //     } else {
    //       wdhours.push({
    //         day: ind.logTime,
    //         hour: 0,
    //         total: 24 - ind.hourNum,
    //         placeholder: '剩余' + (24 - ind.hourNum)
    //       });
    //     }
    //   });
    //   // 保存参数
    //   sessionStorage.removeItem('wdhours');
    //   sessionStorage.setItem('wdhours', JSON.stringify(wdhours));
    // },

    // 添加操作
    createData () {
      // 屏蔽重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);

      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            let hours = [
              this.editForm.day1,
              this.editForm.day2,
              this.editForm.day3,
              this.editForm.day4,
              this.editForm.day5,
              this.editForm.day6,
              this.editForm.day7
            ];
            let weeks = this.weekday;
            let params = [];
            weeks.map((item, index) => {
              params.push({
                logTime: weeks[index],
                hourNum: hours[index],
                proId: this.editForm.proId[0],
                proName: this.editForm.proId[1]
              });
            });
            // 添加工时
            this.$http.raw('api/batchWorks', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                this.$message({
                  message: '添加成功！',
                  type: 'success'
                });
                // 关闭弹窗
                this.dialogFormVisible = false;
                // 刷新列表
                this.getYearDataByPage();
                this.getMonthDataByPage();
                this.getmenusDataByPage();
              }
            }).catch(err => {
              if (err === undefined) {
                this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    },

    // 计算剩余年度工时
    getYearSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计工时';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' H';
        } else {
          sums[index] = 'N/A';
        }
      });
      return sums;
    },

    // 计算剩余月度工时
    getMonthSummaries (param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计工时';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' H';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },

    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
        }
        return i;
      }
    },

    // 日期范围
    nextWeek () {
      let monthEnd = moment(new Date())
        .endOf('month')
        .format('YYYY-MM-DD');
      let day = moment(monthEnd).format('dddd');
      if (day === 'Monday') {
        this.endDay = moment(monthEnd)
          .add(12, 'days')
          .format('YYYY-MM-DD');
      }
      if (day === 'Tuesday') {
        this.endDay = moment(monthEnd)
          .add(11, 'days')
          .format('YYYY-MM-DD');
      }
      if (day === 'Wednesday') {
        this.endDay = moment(monthEnd)
          .add(10, 'days')
          .format('YYYY-MM-DD');
      }
      if (day === 'Thursday') {
        this.endDay = moment(monthEnd)
          .add(9, 'days')
          .format('YYYY-MM-DD');
      }
      if (day === 'Friday') {
        this.endDay = moment(monthEnd)
          .add(8, 'days')
          .format('YYYY-MM-DD');
      }
      if (day === 'Saturday') {
        this.endDay = moment(monthEnd)
          .add(7, 'days')
          .format('YYYY-MM-DD');
      }
      if (day === 'Sunday') {
        this.endDay = moment(monthEnd)
          .add(6, 'days')
          .format('YYYY-MM-DD');
      }
    },

    // 获取所有非转签项目
    getProlist () {
      // 获取所有项目数据
      this.$http.raw('api/findAllPros').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.proList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询年度工时
    selYearHandle: function () {
      // 收集请求数据
      let params = {
        year: moment(this.formInline.year).format('YYYY') === 'Invalid date' ? moment().format('YYYY') : moment(this.formInline.year).format('YYYY'),
        proId: this.formInline.proId,
        pageNum: this.yearCurrentPage,
        pageSize: this.yearPageSize
      };

      // 根据项目ID获取分页数据
      this.$http.raw('api/findYearWorks', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.yearTotal = datas.total;
          // 数据结果集
          this.yearData = this.yearLists(datas.list);

          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.yearCurrentPage !== 1) {
            // 当前页减一
            this.yearCurrentPage -= 1;
            // 调用自己
            this.getYearDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 年份工时过滤
    yearLists (data) {
      let yearLists = [];
      data.map((item, index) => {
        data.map(key => {
          if (item.proId === key.proId) {
            yearLists.push({
              proId: item.proId,
              proName: item.proName,
              month1: 0,
              month2: 0,
              month3: 0,
              month4: 0,
              month5: 0,
              month6: 0,
              month7: 0,
              month8: 0,
              month9: 0,
              month10: 0,
              month11: 0,
              month12: 0
            });
          }
        });
      });
      return this.yearPage(yearLists, data);
    },

    // 匹配过滤合计
    yearPage (yearLists, data) {
      yearLists.map((item, index) => {
        data.map(key => {
          if (item.proId === key.proId) {
            if (key.logTime === '1') {
              yearLists[index].month1 += key.hourNum;
            }
            if (key.logTime === '2') {
              yearLists[index].month2 += key.hourNum;
            }
            if (key.logTime === '3') {
              yearLists[index].month3 += key.hourNum;
            }
            if (key.logTime === '4') {
              yearLists[index].month4 += key.hourNum;
            }
            if (key.logTime === '5') {
              yearLists[index].month5 += key.hourNum;
            }
            if (key.logTime === '6') {
              yearLists[index].month6 += key.hourNum;
            }
            if (key.logTime === '7') {
              yearLists[index].month7 = key.hourNum;
            }
            if (key.logTime === '8') {
              yearLists[index].month8 += key.hourNum;
            }
            if (key.logTime === '9') {
              yearLists[index].month9 += key.hourNum;
            }
            if (key.logTime === '10') {
              yearLists[index].month10 += key.hourNum;
            }
            if (key.logTime === '11') {
              yearLists[index].month11 += key.hourNum;
            }
            if (key.logTime === '12') {
              yearLists[index].month12 += key.hourNum;
            }
          }
        });
      });

      let arr = this.filterArr(yearLists, 'proId');
      return arr;
    },

    // 过滤器
    filterArr (arr, name) {
      let hash = {};
      return arr.reduce((ss, item) => {
        // reduce累计器, ss是具体满足条件后返回的数据, item是数组依次循环的每一项
        // eslint-disable-next-line no-unused-expressions
        hash[item[name]] ? '' : (hash[item[name]] = true && ss.push(item));
        // 1、判断对象的键值是否存在
        return ss;
      }, []);
    },

    // 查询月度工时
    selMonthHandle: function () {
      // 收集请求数据
      let params = {
        year: moment(this.formInline.month).format('YYYY') === 'Invalid date' ? moment().format('YYYY') : moment(this.formInline.month).format('YYYY'),
        month: moment(this.formInline.month).format('MM') === 'Invalid date' ? moment().format('MM') : moment(this.formInline.month).format('MM'),
        proId: this.formInline.proId,
        pageNum: this.monthCurrentPage,
        pageSize: this.monthPageSize
      };

      // 根据项目ID获取分页数据
      this.$http.raw('api/findMonthWorks', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.monthTotal = datas.total;
          // 数据结果集
          this.monthData = datas.list;

          // 数据结果集
          this.monthData = this.monthLists(datas.list);

          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.monthCurrentPage !== 1) {
            // 当前页减一
            this.monthCurrentPage -= 1;
            // 调用自己
            this.getMonthDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 月份过滤
    monthLists (data) {
      let monthLists = [];
      data.map((item, index) => {
        data.map(key => {
          if (item.proId === key.proId) {
            monthLists.push({
              proId: item.proId,
              proName: item.proName,
              day1: 0,
              day2: 0,
              day3: 0,
              day4: 0,
              day5: 0,
              day6: 0,
              day7: 0,
              day8: 0,
              day9: 0,
              day10: 0,
              day11: 0,
              day12: 0,
              day13: 0,
              day14: 0,
              day15: 0,
              day16: 0,
              day17: 0,
              day18: 0,
              day19: 0,
              day20: 0,
              day21: 0,
              day22: 0,
              day23: 0,
              day24: 0,
              day25: 0,
              day26: 0,
              day27: 0,
              day28: 0,
              day29: 0,
              day30: 0,
              day31: 0
            });
          }
        });
      });
      return this.monthPage(monthLists, data);
    },

    monthPage (monthLists, data) {
      monthLists.map((item, index) => {
        data.map(key => {
          if (item.proId === key.proId) {
            if (key.logTime === '1') {
              monthLists[index].day1 += key.hourNum;
            }
            if (key.logTime === '2') {
              monthLists[index].day2 += key.hourNum;
            }
            if (key.logTime === '3') {
              monthLists[index].day3 += key.hourNum;
            }
            if (key.logTime === '4') {
              monthLists[index].day4 += key.hourNum;
            }
            if (key.logTime === '5') {
              monthLists[index].day5 += key.hourNum;
            }
            if (key.logTime === '6') {
              monthLists[index].day6 += key.hourNum;
            }
            if (key.logTime === '7') {
              monthLists[index].day7 = key.hourNum;
            }
            if (key.logTime === '8') {
              monthLists[index].day8 += key.hourNum;
            }
            if (key.logTime === '9') {
              monthLists[index].day9 += key.hourNum;
            }
            if (key.logTime === '10') {
              monthLists[index].day10 += key.hourNum;
            }
            if (key.logTime === '11') {
              monthLists[index].day11 += key.hourNum;
            }
            if (key.logTime === '12') {
              monthLists[index].day12 += key.hourNum;
            }
            if (key.logTime === '13') {
              monthLists[index].day13 += key.hourNum;
            }
            if (key.logTime === '14') {
              monthLists[index].day14 += key.hourNum;
            }
            if (key.logTime === '15') {
              monthLists[index].day15 += key.hourNum;
            }
            if (key.logTime === '16') {
              monthLists[index].day16 += key.hourNum;
            }
            if (key.logTime === '17') {
              monthLists[index].day17 += key.hourNum;
            }
            if (key.logTime === '18') {
              monthLists[index].day18 += key.hourNum;
            }
            if (key.logTime === '19') {
              monthLists[index].day19 = key.hourNum;
            }
            if (key.logTime === '20') {
              monthLists[index].day20 += key.hourNum;
            }
            if (key.logTime === '21') {
              monthLists[index].day21 += key.hourNum;
            }
            if (key.logTime === '22') {
              monthLists[index].day22 += key.hourNum;
            }
            if (key.logTime === '23') {
              monthLists[index].day23 += key.hourNum;
            }
            if (key.logTime === '24') {
              monthLists[index].day24 += key.hourNum;
            }
            if (key.logTime === '25') {
              monthLists[index].day25 += key.hourNum;
            }
            if (key.logTime === '26') {
              monthLists[index].day26 += key.hourNum;
            }
            if (key.logTime === '27') {
              monthLists[index].day27 += key.hourNum;
            }
            if (key.logTime === '28') {
              monthLists[index].day28 += key.hourNum;
            }
            if (key.logTime === '29') {
              monthLists[index].day29 += key.hourNum;
            }
            if (key.logTime === '30') {
              monthLists[index].day30 += key.hourNum;
            }
            if (key.logTime === '31') {
              monthLists[index].day31 = key.hourNum;
            }
          }
        });
      });

      let arr = this.filterArr(monthLists, 'proId');
      return arr;
    },

    // 查询个人工时记录
    selHandle: function () {
      let _this = this;
      let location = _this.$store.state.userinfo.location;
      let params;
      if (location === '全部') {
        params = {
          userId: '',
          logTime: moment(this.formInline.logTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.logTime).format('YYYY-MM-DD'),
          proId: this.formInline.proId,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      } else {
        // 收集请求参数
        params = {
          userId: _this.$store.state.userinfo.userId,
          logTime: moment(this.formInline.logTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.logTime).format('YYYY-MM-DD'),
          proId: this.formInline.proId,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      }
      // 根据项目ID获取分页数据
      this.$http.raw('api/findWorksByTimeAndProId', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.menusData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 刷新年度页面数据
    getYearDataByPage () {
      this.formInline.year = moment().format('YYYY');
      // 收集请求信息
      let params = {
        year: this.formInline.year,
        proId: this.formInline.proId,
        pageNum: this.yearCurrentPage,
        pageSize: this.yearPageSize
      };
      // 获取分页数据
      this.$http.raw('api/findYearWorks', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.yearTotal = datas.total;
          // 数据结果集
          this.yearData = this.yearLists(datas.list);
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.yearCurrentPage !== 1) {
            // 当前页减一
            this.yearCurrentPage -= 1;
            // 调用自己
            this.getYearDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    yearHandleSizeChange (val) {
      this.yearPageSize = val;
      // 调用刷新页面
      this.getYearDataByPage();
    },
    // 当前页码
    yearHandleCurrentChange (val) {
      this.yearCurrentPage = val;
      // 调用
      this.getYearDataByPage();
    },

    // 刷新月度页面数据
    getMonthDataByPage () {
      this.formInline.month = moment().format('YYYY-MM');
      // 收集请求信息
      let params = {
        year: moment().format('YYYY'),
        month: moment().format('MM'),
        proId: this.formInline.proId,
        pageNum: this.monthCurrentPage,
        pageSize: this.monthPageSize
      };
      // 获取分页数据
      this.$http.raw('api/findMonthWorks', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.monthTotal = datas.total;
          this.monthData = this.monthLists(datas.list);
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.monthCurrentPage !== 1) {
            // 当前页减一
            this.monthCurrentPage -= 1;
            // 调用自己
            this.getmenusDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    monthHandleSizeChange (val) {
      this.monthPageSize = val;
      // 调用刷新页面
      this.getMonthDataByPage();
    },
    // 当前页码
    monthHandleCurrentChange (val) {
      this.monthCurrentPage = val;
      // 调用
      this.getMonthDataByPage();
    },

    // 刷新页面数据
    getmenusDataByPage () {
      let _this = this;
      let location = _this.$store.state.userinfo.location;
      let params;
      if (location === '全部') {
        params = {
          userId: '',
          logTime: moment(this.formInline.logTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.logTime).format('YYYY-MM-DD'),
          proId: this.formInline.proId,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      } else {
        // 收集请求参数
        params = {
          userId: _this.$store.state.userinfo.userId,
          logTime: moment(this.formInline.logTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.logTime).format('YYYY-MM-DD'),
          proId: this.formInline.proId,
          pageNum: _this.currentPage,
          pageSize: _this.pageSize
        };
      }
      // 收集请求信息
      // let params = {
      //   logTime: moment(this.formInline.logTime).format('YYYY-MM-DD') === 'Invalid date' ? '' : moment(this.formInline.logTime).format('YYYY-MM-DD'),
      //   proId: this.formInline.proId,
      //   pageNum: this.currentPage,
      //   pageSize: this.pageSize
      // };
      // 获取分页数据
      this.$http.raw('api/findWorksByTimeAndProId', params)
        .then(res => {
          console.log(res);
          let { code, datas } = res;
          if (code === 0) {
            this.total = datas.total;
            this.menusData = datas.list;
            // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
            if (!datas.list.length && this.currentPage !== 1) {
              // 当前页减一
              this.currentPage -= 1;
              // 调用自己
              this.getmenusDataByPage();
            }
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getmenusDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getmenusDataByPage();
    }
  }
};
</script>

<style lang='scss'>
@import './index.scss';
</style>
